<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  
  <title>java的四种引用类型 | Eetal&#39;s Blog</title>

  <!-- keywords -->
  

  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  <meta name="description" content="欢迎查看Eetal的第十四篇博客–java的四种引用类型 引用队列ReferenceQueue,引用队列内部维护一个Lock锁，除了强引用，其他类型引用都包含一个可以传入引用队列的构造函数引用的对象在即将被回收时，会把绑定了引用队列的引用加入引用队列然后回收该对象，因为这时其会变为InActive（死亡 ） Reference抽象类123456789101112131415161718192021">
<meta property="og:type" content="article">
<meta property="og:title" content="java的四种引用类型">
<meta property="og:url" content="http://eetal.gitee.io/blog/2019/03/30/java的四种引用类型/index.html">
<meta property="og:site_name" content="Eetal&#39;s Blog">
<meta property="og:description" content="欢迎查看Eetal的第十四篇博客–java的四种引用类型 引用队列ReferenceQueue,引用队列内部维护一个Lock锁，除了强引用，其他类型引用都包含一个可以传入引用队列的构造函数引用的对象在即将被回收时，会把绑定了引用队列的引用加入引用队列然后回收该对象，因为这时其会变为InActive（死亡 ） Reference抽象类123456789101112131415161718192021">
<meta property="og:locale" content="default">
<meta property="og:updated_time" content="2019-03-31T08:29:15.890Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="java的四种引用类型">
<meta name="twitter:description" content="欢迎查看Eetal的第十四篇博客–java的四种引用类型 引用队列ReferenceQueue,引用队列内部维护一个Lock锁，除了强引用，其他类型引用都包含一个可以传入引用队列的构造函数引用的对象在即将被回收时，会把绑定了引用队列的引用加入引用队列然后回收该对象，因为这时其会变为InActive（死亡 ） Reference抽象类123456789101112131415161718192021">
  
    <link rel="alternative" href="/atom.xml" title="Eetal&#39;s Blog" type="application/atom+xml">
  
  
    <link rel="icon" href="http://www.yangyitao.top/FiveChess/resource/ico/favicon.ico">
  
  <link rel="stylesheet" href="/blog/css/style.css">
  
  

  <script src="//cdn.bootcss.com/require.js/2.3.2/require.min.js"></script>
  <script src="//cdn.bootcss.com/jquery/3.1.1/jquery.min.js"></script>

  
</head>
<body>
  <div id="container">
    <div id="particles-js"></div>
    <div class="left-col">
    <div class="overlay"></div>
<div class="intrude-less">
	<header id="header" class="inner">
		<a href="/" class="profilepic">
			
			<img lazy-src="/blog/images/head.jpg" class="js-avatar">
			
		</a>

		<hgroup>
		  <h1 class="header-author"><a href="/">Eetal</a></h1>
		</hgroup>

		
		<p class="header-subtitle">java coder</p>
		

		
			<div class="switch-btn">
				<div class="icon">
					<div class="icon-ctn">
						<div class="icon-wrap icon-house" data-idx="0">
							<div class="birdhouse"></div>
							<div class="birdhouse_holes"></div>
						</div>
						<div class="icon-wrap icon-ribbon hide" data-idx="1">
							<div class="ribbon"></div>
						</div>
						
						<div class="icon-wrap icon-link hide" data-idx="2">
							<div class="loopback_l"></div>
							<div class="loopback_r"></div>
						</div>
						
						
					</div>
					
				</div>
				<div class="tips-box hide">
					<div class="tips-arrow"></div>
					<ul class="tips-inner">
						<li>菜单</li>
						<li>标签</li>
						
						<li>友情链接</li>
						
						
					</ul>
				</div>
			</div>
		

		<div class="switch-area">
			<div class="switch-wrap">
				<section class="switch-part switch-part1">
					<nav class="header-menu">
						<ul>
						
							<li><a href="/blog/">Home</a></li>
				        
							<li><a href="/blog/archives">Archives</a></li>
				        
						</ul>
					</nav>
					<nav class="header-nav">
						<div class="social">
							
						</div>
					</nav>
				</section>
				
				
				<section class="switch-part switch-part2">
					<div class="widget tagcloud" id="js-tagcloud">
						
					</div>
				</section>
				
				
				
				<section class="switch-part switch-part3">
					<div id="js-friends">
					
			          <a target="_blank" class="main-nav-link switch-friends-link" href="https://github.com/smackgg/hexo-theme-smackdown">smackdown</a>
			        
			        </div>
				</section>
				

				
			</div>
		</div>
	</header>				
</div>
    </div>
    <div class="mid-col">
      <nav id="mobile-nav">
  	<div class="overlay">
  		<div class="slider-trigger"></div>
  		<h1 class="header-author js-mobile-header hide">Eetal</h1>
  	</div>
	<div class="intrude-less">
		<header id="header" class="inner">
			<div class="profilepic">
				<img lazy-src="/blog/images/head.jpg" class="js-avatar">
			</div>
			<hgroup>
			  <h1 class="header-author">Eetal</h1>
			</hgroup>
			
			<p class="header-subtitle">java coder</p>
			
			<nav class="header-menu">
				<ul>
				
					<li><a href="/blog/">Home</a></li>
		        
					<li><a href="/blog/archives">Archives</a></li>
		        
		        <div class="clearfix"></div>
				</ul>
			</nav>
			<nav class="header-nav">
				<div class="social">
					
				</div>
			</nav>
		</header>				
	</div>
</nav>
      <div class="body-wrap"><article id="post-java的四种引用类型" class="article article-type-post" itemscope itemprop="blogPost">
  
    <div class="article-meta">
      <a href="/blog/2019/03/30/java的四种引用类型/" class="article-date">
  	<time datetime="2019-03-30T08:36:49.177Z" itemprop="datePublished">2019-03-30</time>
</a>
    </div>
  
  <div class="article-inner">
    
      <input type="hidden" class="isFancy" />
    
    
      <header class="article-header">
        
  
    <h1 class="article-title" itemprop="name">
      java的四种引用类型
      
    </h1>
  

      </header>
      
      <div class="article-info article-info-post">
        
        

        
        <div class="clearfix"></div>
      </div>
      
    
    <div class="article-entry" itemprop="articleBody">
      
        <p>欢迎查看Eetal的第十四篇博客–java的四种引用类型</p>
<h2 id="引用队列"><a href="#引用队列" class="headerlink" title="引用队列"></a>引用队列</h2><p>ReferenceQueue,引用队列内部维护一个Lock锁，除了强引用，其他类型引用都包含一个可以传入引用队列的构造函数<br>引用的对象在即将被回收时，会把绑定了引用队列的引用加入引用队列<br>然后回收该对象，因为这时其会变为InActive（死亡 ）</p>
<h2 id="Reference抽象类"><a href="#Reference抽象类" class="headerlink" title="Reference抽象类"></a>Reference抽象类</h2><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br></pre></td><td class="code"><pre><span class="line">   /*引用实例处于四种可能的内部状态之一：</span><br><span class="line">*</span><br><span class="line">*活性：由垃圾收集器进行特殊处理。一些</span><br><span class="line">*收集器检测到referent已更改为适当的状态，</span><br><span class="line">*它将更改实例的状态为挂起或不活动，具体取决于实例是否在队列中注册已创建。</span><br><span class="line">*在前一种情况下，它还将实例添加到挂起的引用列表。</span><br><span class="line">*新创建的实例处于活动状态。</span><br><span class="line">*</span><br><span class="line">*挂起：挂起引用列表的元素，等待被引用处理程序线程排队。</span><br><span class="line">*未注册的实例从未处于这种状态。</span><br><span class="line">*</span><br><span class="line">*排队：处于等待加入引用队列的等待队列，（因为加入引用队列的方法需要获取锁）</span><br><span class="line">*</span><br><span class="line">*不活动：没什么可做的。一旦一个实例变为非活动状态，状态永远不会改变。</span><br><span class="line">*</span><br><span class="line">*状态在队列和下一个字段中编码如下：</span><br><span class="line">*</span><br><span class="line">*active:queue=referencequeue，注册实例，</span><br><span class="line">*或referencequeue.null，如果它未注册到队列；</span><br><span class="line">*next=NULL。</span><br><span class="line">*</span><br><span class="line">*挂起：queue=referencequeue，实例已注册；</span><br><span class="line">*next=this</span><br><span class="line">*</span><br><span class="line">*排队：queue=referencequeue.enqueued；</span><br><span class="line">*next=following instance</span><br><span class="line">*在队列中，或者在列表的末尾。</span><br><span class="line">*</span><br><span class="line">*非活动：queue=referencequeue.null；</span><br><span class="line">*next=this。</span><br><span class="line">*</span><br><span class="line">*使用此方案，收集器只需按顺序检查下一个字段确定引用实例是否需要特殊处理：如果下一个字段为空，则实例处于活动状态；</span><br><span class="line">*如果为非空，收集器应该正常处理该实例。</span><br><span class="line">*确保并发收集器可以发现活动引用不干扰可能应用的应用程序线程的对象enqueue（）方法到这些对象，</span><br><span class="line">*收集器应链接通过发现的字段发现的对象。发现的字段还用于链接挂起列表中的引用对象。</span><br><span class="line">*/</span><br><span class="line"></span><br><span class="line">Reference(T referent, ReferenceQueue&lt;? super T&gt; queue) &#123;</span><br><span class="line">	this.referent = referent;</span><br><span class="line">	this.queue = (queue == null) ? ReferenceQueue.NULL : queue;</span><br><span class="line">&#125;</span><br><span class="line">private T referent;         /* Treated specially by GC */</span><br><span class="line"></span><br><span class="line">volatile ReferenceQueue&lt;? super T&gt; queue;</span><br></pre></td></tr></table></figure>
<p>网上大部分博客对于四种引用的说法都不准确，不去关心为何垃圾回收时会将对应引用加入对应引用队列<br>这里留意抽象类里的注释Treated specially by GC(被gc特殊对待)<br>具体过程就是，当满足了该引用对象被回收的条件时（在没有强引用引用他的前提下）<br>将该引用加入引用队列，并且该引用队列不再引用该对象（清除，注意虚引用在此处不同，虚引用需要等到对象上所有的引用清除以后才清除）<br>同时该对象也会变为死亡状态，会被垃圾回收器回收<br>接下来讲讲各个引用的条件</p>
<h2 id="强引用"><a href="#强引用" class="headerlink" title="强引用"></a>强引用</h2><p>没什么好说的<br>java默认的引用类型，就是强引用类型<br>比如<br>Object o;<br>这就是一个强引用，只是没有引用对象</p>
<h2 id="软引用"><a href="#软引用" class="headerlink" title="软引用"></a>软引用</h2><p>被软引用的对象在垃圾回收器线程扫描到且当jvm内存不足时，该软引用就会不再引用该对象<br>软引用可以与引用队列搭配使用<br>使用方式（传递对象）</p>
<p>SoftReference<object> sr = new SoftReference<object>(new Object());<br>sr.get(); //返回软引用对象，此处为Object类型</object></object></p>
<h2 id="弱引用"><a href="#弱引用" class="headerlink" title="弱引用"></a>弱引用</h2><p>被弱引用的对象在垃圾回收器线程扫描到时，该弱引用就会不再引用该对象<br>弱引用可以与引用队列搭配使用</p>
<p>WeakReference<object> wr = new WeakReference<object>(new Object());<br>wr.get(); //返回弱引用对象，此处为Object类型</object></object></p>
<h2 id="虚引用"><a href="#虚引用" class="headerlink" title="虚引用"></a>虚引用</h2><p>虚引用并不影响对象的生命周期<br>虚引用必须与引用队列搭配使用<br>虚引用并不可访问引用对象，get总是返回null<br>虚引用需要等到对象上所有的引用清除以后才清除<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">public class PhantomReference&lt;T&gt; extends Reference&lt;T&gt; &#123;</span><br><span class="line"></span><br><span class="line">	/**</span><br><span class="line">	 * Returns this reference object<span class="string">'s referent.  Because the referent of a</span></span><br><span class="line"><span class="string">	 * phantom reference is always inaccessible, this method always returns</span></span><br><span class="line"><span class="string">	 * &lt;code&gt;null&lt;/code&gt;.</span></span><br><span class="line"><span class="string">	 *</span></span><br><span class="line"><span class="string">	 * @return  &lt;code&gt;null&lt;/code&gt;</span></span><br><span class="line"><span class="string">	 */</span></span><br><span class="line"><span class="string">	public T get() &#123;</span></span><br><span class="line"><span class="string">		return null;</span></span><br><span class="line"><span class="string">	&#125;</span></span><br><span class="line"><span class="string">	.....</span></span><br><span class="line"><span class="string">&#125;</span></span><br></pre></td></tr></table></figure></p>
<p>ReferenceQueue queue = new ReferenceQueue ();<br>PhantomReference pr = new PhantomReference (new Object(), queue);<br>pr.get();//返回null</p>
<h2 id="验证代码"><a href="#验证代码" class="headerlink" title="验证代码"></a>验证代码</h2><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line">public class RefferenceDemo &#123;</span><br><span class="line">	static ReferenceQueue&lt;Object&gt; rq = new ReferenceQueue&lt;Object&gt;();</span><br><span class="line">	static Reference wr;</span><br><span class="line">	public static void <span class="function"><span class="title">test</span></span>() &#123;</span><br><span class="line">		wr = new WeakReference(new Object(),rq);</span><br><span class="line">		System.out.println(wr.get().hashCode());</span><br><span class="line">		</span><br><span class="line">	&#125;</span><br><span class="line">	public static void main(String[] args) &#123;</span><br><span class="line">		<span class="built_in">test</span>();</span><br><span class="line">		//Object o = wr.get(); //解除注释会增加强引用，则调用gc也不会回收，引用队列poll为null</span><br><span class="line">								//注释没有强引用，则调用gc会回收，引用队列poll为不为null</span><br><span class="line">		System.gc();</span><br><span class="line">		System.out.println(wr.get());</span><br><span class="line">		wr = rq.poll();</span><br><span class="line">		System.out.println(<span class="string">"poll:"</span>+wr+<span class="string">",getValue:"</span>+wr.get());</span><br><span class="line">		System.out.println(<span class="string">"poll:"</span>+rq.poll());</span><br><span class="line">		System.out.println(wr.get());</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>输出<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">118352462</span><br><span class="line">null</span><br><span class="line">poll:java.lang.ref.WeakReference@5c647e05,getValue:null</span><br><span class="line">poll:null</span><br><span class="line">null</span><br></pre></td></tr></table></figure></p>
<h3 id="请移步"><a href="#请移步" class="headerlink" title="请移步"></a>请移步</h3><p>个人主页: <a href="http://yangyitao.top" target="_blank" rel="noopener">yangyitao.top</a></p>

      
    </div>
    
  </div>
  
    
<nav id="article-nav">
  
    <a href="/blog/2019/03/31/手撕AVL树/" id="article-nav-newer" class="article-nav-link-wrap">
      <strong class="article-nav-caption">&lt;</strong>
      <div class="article-nav-title">
        
          手撕AVL树
        
      </div>
    </a>
  
  
    <a href="/blog/2019/03/30/GC与垃圾回收分代/" id="article-nav-older" class="article-nav-link-wrap">
      <div class="article-nav-title">GC与垃圾回收分代</div>
      <strong class="article-nav-caption">&gt;</strong>
    </a>
  
</nav>

  
</article>


<div class="ds-share share" data-thread-key="java的四种引用类型" data-title="java的四种引用类型" data-url="http://eetal.gitee.io/blog/blog/2019/03/30/java的四种引用类型/"  data-images="/blog/images/head.jpg" data-content="java的四种引用类型">
    <div class="ds-share-inline">
      <ul  class="ds-share-icons-16">
      	<li data-toggle="ds-share-icons-more"><a class="ds-more" href="javascript:void(0);">分享到：</a></li>
        <li><a class="ds-weibo" href="javascript:void(0);" data-service="weibo">微博</a></li>
        <li><a class="ds-qzone" href="javascript:void(0);" data-service="qzone">QQ空间</a></li>
        <li><a class="ds-qqt" href="javascript:void(0);" data-service="qqt">腾讯微博</a></li>
        <li><a class="ds-wechat" href="javascript:void(0);" data-service="wechat">微信</a></li>
      </ul>
      <div class="ds-share-icons-more">
      </div>
    </div>
 </div>
 





</div>
      <footer id="footer">
  <div class="outer">
    <div id="footer-info">
      <div class="footer-left">
        &copy; 2019 Eetal
      </div>
        <div class="footer-right">
          <a href="http://hexo.io/" target="_blank">Hexo</a>  Theme <a href="https://github.com/smackgg/hexo-theme-smackdown" target="_blank">Smackdown</a>
        </div>
    </div>
  </div>
</footer>
    </div>
    
  <link rel="stylesheet" href="/blog/fancybox/jquery.fancybox.css">


<script>
	var yiliaConfig = {
		fancybox: true,
		mathjax: true,
		animate: true,
		isHome: false,
		isPost: true,
		isArchive: false,
		isTag: false,
		isCategory: false,
		open_in_new: false
	}
</script>
<script src="/blog/js/main.js"></script>



<script type="text/x-mathjax-config">
MathJax.Hub.Config({
    tex2jax: {
        inlineMath: [ ['$','$'], ["\\(","\\)"]  ],
        processEscapes: true,
        skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
    }
});

MathJax.Hub.Queue(function() {
    var all = MathJax.Hub.getAllJax(), i;
    for(i=0; i < all.length; i += 1) {
        all[i].SourceElement().parentNode.className += ' has-jax';                 
    }       
});
</script>

<script src="//cdn.bootcss.com/mathjax/2.7.0/MathJax.js"></script>


  </div>
</body>
</html>